--
-- Author: yao.chen
-- Date: 2018-09-20 18:00:00
--
-- RewardDrawPanel
--

local RewardDrawPanel = app.mvc.createPanelClass(...)

local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local RewardMiraculousCard = import(".RewardMiraculousCard")
local RewardOpenCardView = import(".RewardOpenCardView")
local RewardMiraculousCardRender = import(".renders.RewardMiraculousCardRender")
local ResRender = require("app.widget.renders.ResRender")

local CARD_MAX_NUMBER = 3
local string_format = string.format

function RewardDrawPanel.create(data, node)
    local sprite = RewardDrawPanel.extend(node or cc.CSLoader:createNode(Res.RewardDrawPanel_Node_draw, true))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end

function RewardDrawPanel:init(data)
	self.super.init(self, data)
    self:setContentSize(self._ui.Panel:getContentSize())
	self._loadingBar = self._ui["Panel/Panel_bom/bar/LoadingBar"]	-- 概率进度条	
	self._loadingBarTip = self._ui["Panel/Panel_bom/tlt"]	-- 概率说明		
	self._numPanel = self._ui["Panel/Panel_bom/num"]	-- 问号
	self._numPanel:setString(L"?")
    self._numBG = self._ui["Panel/Panel_bom/bar/bg1"]
	self._cardNumTip = self._ui["Panel/tips"]	-- 卡牌拥有说明
	self._numBG:setTouchEnabled(true)
	self._numBG:addTouchEventListener(function(sender, eventType)
		if eventType == ccui.TouchEventType.ended then
			self:showProbTips()
		end
	end)

	local function openEvent(sender, eventType)
		if eventType == ccui.TouchEventType.ended then
			local tag = sender:getTag()
			if self._data and self._data.statusCard[tag] ~= 1 then
				AM.playClickItemSound()
				display.pushToast(L("activityCardTips5"))
				return 
            end

            -- 选中的翻滚特效
            self:playSelectedAni(tag, function()
                local viewName = RewardOpenCardView:getViewName()
                local view = UIHandler:getPopupUiByKey(viewName)
                if not cc.isDead(view) then
                    return
                end
            
                view = RewardOpenCardView.new()
                view:onCloseView(function(sender)
                    UIHandler:removePopupUiByKey(sender:getViewName())
                end)
                UIHandler:addPopupUi(view, view:getViewName())
                view:onOperate(self._onOperate)
				view:setTag(tag)
                view:setData(self._data)
                view:show()
            end)
		end
	end

	-- 三张卡牌
	self._cardArray = {}
	local card
	for i = 1, CARD_MAX_NUMBER do
		card = RewardMiraculousCard.new(self._ui["Panel/card_" .. i]) 
		card:findChild("Panel"):addTouchEventListener(openEvent)
		card:findChild("Panel"):setTag(i)
        card:getTimeline():gotoFrameAndPause(0)
		table.insert(self._cardArray, card)
	end

    self._selectCard = RewardMiraculousCardRender.create(self._ui.card_big)
    self._selectCardPos = cc.p(self._selectCard:getPosition())
    self._selectCard:setVisible(false)
    self._selectCard:getTimeline():gotoFrameAndPause(0)
    self._selectCard:setParticlePlay(false)

	self._resRender = ResRender.create(self._ui.Panel_money)
	self._resRender:setData({type = Enums.TipsType.daibi, id = Enums.PropType.gold, num = 0})

	self:setPanelVisible(false) -- 默认先隐藏UI等收到服务器返回信息后再显示
end

function RewardDrawPanel:onOperate(cb)
	self._onOperate = cb
end

function RewardDrawPanel:setData(data)
    local tempData = self:makeData(data)
    if not tempData then return end
	self._data = tempData
	self:refresh(tempData)
	self:setPanelVisible(true)
    if tempData then
        local viewName = RewardOpenCardView:getViewName()
        local view = UIHandler:getPopupUiByKey(viewName)
        if cc.isDead(view) then
			UIHandler:removePopupUiByKey(viewName)
		else
            view:setData(tempData)
        end
    end
end

function RewardDrawPanel:makeData(data)
    if not data then return end
    local tempData = data
    tempData.cardScale = {}
    tempData.cardPositon = {}
    for i = 1, CARD_MAX_NUMBER do
        local scale = self._cardArray[i]:getScale()
        table.insert(tempData.cardScale, scale)
        local pos = cc.p(self._cardArray[i]:getPosition())
        table.insert(tempData.cardPositon, pos)
    end
    return tempData
end

function RewardDrawPanel:refresh(data)
	if data then
		local ownCount = 0	
		for i = 1, CARD_MAX_NUMBER do
			local v = data.statusCard[i]
			self._cardArray[i]:setData(v, data.timeStr)
			if v == 1 then
				ownCount = ownCount + 1
			end
		end 				
		self:setGoldCardProb(data.nowCof)	
		self:setOwnCount(ownCount)
        self:setGoldPanel()
	else
		self:setGoldCardProb(0)
		self:setOwnCount(0)
	end	
end

function RewardDrawPanel:showProbTips()
	local dataTemp = {
		name=L("lua_code_text_440"),
		string1 = L("activityCardTips6"),
	}
	
	if self.eventTips then
		self.eventTips:setData(dataTemp)
	else
		self.eventTips = NewRareInfoView.create()
		self.eventTips:setData(dataTemp)
		self:addChild(self.eventTips)
	
		local triggerNodeBoundingBox = self._numBG:getBoundingBox()
		local worldPosTemp = self._numBG:getParent():convertToWorldSpace(cc.p(triggerNodeBoundingBox.x, triggerNodeBoundingBox.y))
		triggerNodeBoundingBox.x = worldPosTemp.x
		triggerNodeBoundingBox.y = worldPosTemp.y
		display.adjustNodePos(triggerNodeBoundingBox, self.eventTips , -66, 5)
	
		-- 点击空白区域关闭
		display.nodeRemoveForNotHit(self.eventTips, function()
			if self.eventTips then
				self.eventTips:removeFromParent()
				self.eventTips = nil
			end
		end)
	end
end

function RewardDrawPanel:setGoldCardProb(percent)
	self._loadingBarTip:setString(string_format(L("activityCardTips1"), percent)) 
	self._loadingBar:setPercent(percent)
end

function RewardDrawPanel:setOwnCount(count)
	self._cardNumTip:setString(string_format(L("activityCardTips2"), count, CARD_MAX_NUMBER))
end

function RewardDrawPanel:playSelectedAni(idx, cb)
	AM.playSoundById(2392)
    self._selectCard:getTimeline():gotoFrameAndPause(0)
    self._selectCard:setScale(self._cardArray[idx]:getScale())
    self._selectCard:setPosition(self._cardArray[idx]:getPosition())
    self._selectCard:setVisible(true)

    local Action_1 = cc.ScaleTo:create(0.333, 1)
    local Action_2 = cc.MoveTo:create(0.333, self._selectCardPos)
    -- 卡牌翻转动画
    -- 持续时间、半径初始值、半径增量、仰角初始值、仰角增量、离x轴的偏移角、离x轴的偏移角的增量
    local Action_3 = cc.OrbitCamera:create(0.333, 10, 0, 0, -360, 0, 0)
    local Actions_1 = cc.Spawn:create(Action_1, Action_2, Action_3)

    local Actions_2 = cc.CallFunc:create(function()
        self._selectCard:setVisible(false)
        self._ui.Image_bg:setVisible(false)
		executeFunc(cb)
	end)
    local actions = cc.Sequence:create(Actions_1, Actions_2)
    self._selectCard:runAction(actions)
end

function RewardDrawPanel:setGoldPanel()
    local money = UD:getGold()
	self._resRender:setNum(money)
end

function RewardDrawPanel:setPanelVisible(b)
	self._ui.Panel:setVisible(b)
end

return RewardDrawPanel